package util;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import models.Category;
import models.Restaurant;
import models.ZipcodeGeo;
import play.Play;

import com.flaptor.indextank.apiclient.IndexTankClient;
import com.flaptor.indextank.apiclient.IndexTankClient.Index;
import com.flaptor.indextank.apiclient.IndexTankClient.Query;
import com.flaptor.indextank.apiclient.IndexTankClient.SearchResults;
import com.javadocmd.simplelatlng.LatLng;

public class IndexTank {

	public static List<Restaurant> performSearch(String kw, ZipcodeGeo zipgeo,
			Category category) throws Exception {
		List<Restaurant> restaurants = new ArrayList<Restaurant>();
		Index index = IndexTank.getRestaurantIndex();
		LatLng latLng = (zipgeo != null) ? zipgeo.getLatLng() : null;
		Query query = Restaurant.queryFor(kw, category, latLng);
		SearchResults results = index.search(query);

		for (Map<String, Object> r : results.results) {
			restaurants.add(new Restaurant(r));
		}
		return restaurants;
	}

	public static Index getRestaurantIndex() {
		String indexTankUrl = (String) Play.configuration.get("indextank.url");
		String factualIndex = (String) Play.configuration
				.get("indextank.index.factual");
		IndexTankClient client = new IndexTankClient(indexTankUrl);
		return client.getIndex(factualIndex);
	}
}
